package com.hpe.manager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import javax.jws.WebMethod;
import javax.jws.WebService;
import com.hpe.bean.Config;
import com.hpe.service.ImapReceiveMailService;

/**
 * <p/>
 * <HR/><B>Modification Block</B>
 * <p/>
 * Version:  1.0.1 <BR>
 * Author: Shaxj
 * Date: 2015/12/1
 * Comments: Created.
 * </P>
 **/

@WebService
public class MailManager {
    private final Logger log = Logger.getLogger(MailManager.class.getName());
    public List<Config> configs = new ArrayList();
    public Runnable runnable = null;
    public ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

    @WebMethod
    public String addMail(Config config) {
        configs.add(config);
        return "success";
    }

    @WebMethod
    public String receiveMail() {
        return "success";
    }

    @WebMethod
    public List<Config> allMailConfig() {
        return configs;
    }

    @WebMethod
    public String deleteConfig() {
        configs = new ArrayList();
        return "success";
    }

    @WebMethod
    public void start() {
        try {
            if (service.isShutdown()) {
                service = Executors.newSingleThreadScheduledExecutor();
            }
            if (runnable == null) {
                runnable = new Runnable() {
                    public void run() {
                        try {
                            System.out.println("开始执行任务 " );
                            ImapReceiveMailService imapReceiveMailService = new ImapReceiveMailService();
                            imapReceiveMailService.getInboxMessage();
                            System.out.println("任务执行完毕 " );
                        } catch (Exception e) {
                            log.info(e.toString());
                        }
                    }
                };
                service.scheduleAtFixedRate(runnable, 2L, 60*15L, TimeUnit.SECONDS);
            }
            log.info("task start!");
        } catch (Exception e) {
            log.info("task start error!");
            e.printStackTrace();
        }
    }

    @WebMethod
    public void shutDown() {
        try {
            service.shutdownNow();
            runnable = null;
            log.info("task shut down!");
        } catch (Exception e) {
            log.info("task shut down error!");
            e.printStackTrace();
        }
    }
}